package algorithm.search.binarysearch;

import algorithm.search.binarysearch.interfaces.ISearch;


import java.util.ArrayList;
import java.util.Random;

/**
 * @author: lancyguy
 * @author cgzh@hotmail.com
 * @param <T> type of the elements to be searched
 */
public class NormalSearcher<T> implements ISearch<T>{
    /**
     * constructor
     */
    public NormalSearcher(){

    }
    /**
     *
     * @param arr array to be searched
     * @param e search this value
     * @return index of the element equals e, if no element found then return -1
     */
    public int search(T[] arr, T e){
        return search(arr,e,0,arr.length-1);
    }

    /**
     *
     * @param arr array to be searched
     * @param e search this value
     * @return indexes of the elements equal e, if no element found then return null
     */
    public int[] searchAll(T[] arr, T e){
        return searchAll(arr,e,0,arr.length-1);
    }
    /**
     *
     * @param arr array to be searched
     * @param e search this value
     * @param head left boundary of the range of the array within which the searching takes place
     * @param end right boundary of the range of the array within which the searching takes place
     * @return index of the element equals e, if no element found then return -1
     */
    public int search(T[] arr, T e, int head, int end){
        if(head>end || head<0 || end>=arr.length)
            return -1;
        for(int i=head;i<=end;i++){
            if(arr[i].equals(e))
                return i;
        }
        return -1;
    }
    /**
     *
     * @param arr array to be searched
     * @param e search this value
     * @param head left boundary of the range of the array within which the searching takes place
     * @param end right boundary of the range of the array within which the searching takes place
     * @return indexes of the elements equal e, if no element found then return null
     */
    public int[] searchAll(T[] arr, T e, int head, int end){
        ArrayList<Integer> resultList = new ArrayList<Integer>();
        for(int i=head;i<=end;i++){
            if(arr[i].equals(e)){
                resultList.add(i);
            }
        }
        int resultSize = resultList.size();
        if(resultSize==0)
            return null;
        int[]  resultArr = new int[resultSize];
        for(int i=0;i<resultSize;i++){
            resultArr[i] = resultList.get(i);
        }
        return resultArr;
    }
}